package com.shanxi.cz.module.biz.controller.admin.mqtt;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@Tag(name = "管理后台 - mqtt消息存储")
@RestController
@RequestMapping("/api/debug")
@Validated
@Slf4j
public class DebugController {
    @Autowired
    private MqttPahoMessageDrivenChannelAdapter mqttInbound;

    @GetMapping("/status")
    @Operation(summary = "MQTT服务状态")
    public String getStatus() {
        StringBuilder status = new StringBuilder();
        status.append("=== MQTT服务状态 ===\n");
        status.append("时间: ").append(new Date()).append("\n");
        status.append("适配器运行状态: ").append(mqttInbound.isRunning()).append("\n");
//        status.append("客户端ID: ").append(mqttInbound.getClientInstance()).append("\n");

        try {
            String[] topics = mqttInbound.getTopic();
            status.append("订阅主题: ").append(String.join(", ", topics)).append("\n");
        } catch (Exception e) {
            status.append("获取主题错误: ").append(e.getMessage()).append("\n");
        }

        return status.toString();
    }

    @GetMapping("/restart")
    @Operation(summary = "手动重启MQTT适配器")
    public String restartMqtt() {
        try {
            log.info("手动重启MQTT适配器");
            mqttInbound.stop();
            Thread.sleep(1000);
            mqttInbound.start();
            return "MQTT适配器重启成功";
        } catch (Exception e) {
            return "重启失败: " + e.getMessage();
        }
    }
}
